﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace SelfMadeMillionaire.Web.Infrastructure.Attributes
{
	[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
	public sealed class RequiredIfAttribute : ValidationAttribute, IClientValidatable
	{
		private string _targetPropertyName;
		private object _targetPropertyCondition;

		public RequiredIfAttribute(string targetPropertyName, object targetPropertyCondition)
		{
			this._targetPropertyName = targetPropertyName;
			this._targetPropertyCondition = targetPropertyCondition;
		}

		protected override ValidationResult IsValid(object value, ValidationContext validationContext)
		{
			var targetProperty = validationContext.ObjectType.GetProperty(_targetPropertyName);
			var targetPropertyValue = targetProperty.GetValue(validationContext.ObjectInstance, null);

			if (object.Equals(targetPropertyValue, _targetPropertyCondition) && value == null)
				return new ValidationResult(ErrorMessage);

			return ValidationResult.Success;
		}

		public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
		{
			var rule = new ModelClientValidationRule();

			rule.ErrorMessage = ErrorMessage;
			rule.ValidationType = "requiredif";
			rule.ValidationParameters.Add("targetpropertyname", this._targetPropertyName);
			rule.ValidationParameters.Add("targetpropertyvalue", this._targetPropertyCondition == null ? "" : this._targetPropertyCondition.ToString().ToLower());

			yield return rule;
		}
	}

}
